package com.xj.demoExcel.easyexcel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelDataConvertException;
import io.vertx.core.json.JsonArray;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class LocationListener extends AnalysisEventListener<Location> {

    List<Location> list = new ArrayList<>();

    /**
     * 解析到一条数据后的操作
     *
     * @param excelMode
     * @param analysisContext
     */
    @Override
    public void invoke(Location excelMode, AnalysisContext analysisContext) {
        System.out.println("解析到1条数据：" + excelMode.toString());
        list.add(excelMode);
    }

    /**
     * excel全部解析完后的操作
     *
     * @param analysisContext
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        JsonArray jsonArray = new JsonArray();
        for (Location obj : list) {
            JsonArray tmpArr = new JsonArray();
            tmpArr.add(obj.getProvince()!=null?obj.getProvince().getData():null);
            tmpArr.add(obj.getCity()!=null?obj.getCity().getData():null);
            tmpArr.add(obj.getCounty()!=null?obj.getProvince().getData():null);

            jsonArray.add(tmpArr);
        }
        System.out.println(jsonArray.encode());
    }

    /**
     * 解析出现异常时的操作
     * @param exception
     * @param context
     */
    @Override
    public void onException(Exception exception, AnalysisContext context) {
        //抛出异常则停止读取。如果这里不抛出异常则 继续读取下一行。
        System.out.println("解析失败，但是继续解析下一行:{}" + exception.getMessage());
        if (exception instanceof ExcelDataConvertException) {
            ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException) exception;
            System.out.println(
                    String.format("第{%s}行，第{%s}列解析异常，数据为:{%s}",
                            excelDataConvertException.getRowIndex(),
                            excelDataConvertException.getColumnIndex(),
                            excelDataConvertException.getCellData()
                    )
            );
        }
    }

    /**
     * 将表头的信息解析出来。和headRowNumber()组合使用。可能会读取多行表头
     *
     * headRowNumber读取下面的数据，invokeHeadMap读取上面的数据
     *
     * @param headMap
     * @param context
     */
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        for (Map.Entry<Integer, String> entry : headMap.entrySet()) {
            System.out.println("key=" + entry.getKey() + " and value=" + entry.getValue());
        }
    }
}
